<template>
    <div>
      <div class="formdata">
        <aside>
          <p>修改头像</p>
          <el-form :model="userinfoForm" ref="changeuserinfoRef">
            <el-form-item :label-width="formLabelWidth" class="addimg" prop="product_img">
            <el-checkbox-group v-model="userinfoForm.user_pic" v-show="false"></el-checkbox-group>
            <img src="../../../assets/上传头像.png" alt="" ref="imgRef">
            <input type="file" style="display:none" ref="iptRef" accept="image/*" @change="oncoverChangeFN">
            <br>
            <el-button type="text" @click="clickipt">添加图片</el-button>
          </el-form-item>
          </el-form>
          <div class="btnplace">
            <el-button @click="resetForm" size="small">重 置</el-button>
            <el-button @click="confimFn" type="primary" size="small">确 定</el-button>
          </div>
        </aside>
      </div>
    </div>
  </template>

<script>
import { getuserinfoAPI, updateavatarAPI } from '@/api'
import { mapActions } from 'vuex'
import imgUrl from '../../../assets/上传头像.png'
export default {
  name: 'admin-category',
  data () {
    return {
      userinfo: {},
      formLabelWidth: '80px',
      userinfoForm: {
        user_pic: ''
      }
    }
  },
  mounted () {
    this.getuserinfo()
  },
  methods: {
    // 获取个人信息
    async getuserinfo () {
      const { data } = await getuserinfoAPI()
      this.userinfo = data.data
    },
    clickipt () {
      this.$refs.iptRef.click()
    },
    oncoverChangeFN (e) {
      const file = e.target.files
      if (file.length === 0) {
        this.userinfoForm.user_pic = null
        this.$refs.imgRef.setAttribute('src', imgUrl)
      } else {
        const fr = new FileReader()
        fr.readAsDataURL(file[0])
        fr.onload = (e) => {
          this.$refs.imgRef.setAttribute('src', e.target.result)
          this.userinfoForm.user_pic = e.target.result
        }
      }
    },
    ...mapActions(['GETUSERINFO']),
    // 点击确定
    confimFn () {
      updateavatarAPI(this.userinfoForm.user_pic).then(({ data }) => {
        if (data.status !== 0) return this.$message.error(data.message)
        this.$message.success(data.message)
        this.GETUSERINFO()
      })
    },
    // 重置按钮 - 重置表单
    resetForm () {
      this.$refs.imgRef.setAttribute('src', imgUrl)
    }
  }
}
</script>

<style scoped>
.formdata {
    width:300px;
    margin: 0 auto;
    text-align: center;
}
.addimg img {
    width: 150px;
    height: 130px;
}
.btnplace {
    margin-left: 93px;
}
</style>
